Ext.onReady(function(){

	var role_sm = new Ext.grid.CheckboxSelectionModel({
        singleSelect: false,
        sortable: false,
        checkOnly: false,
        simpleSelect:false,
        listeners:{
           rowselect:function(this_,rowIndex,record){
                if (panel_panel1_panel1_gridpanel_selModel.getCount()!=0){
                    Ext.Ajax.request({
                        url:'user/attachUserRole.json',
                        params:{
                            id:panel_panel1_panel1_gridpanel_selModel.getSelected().get('id'),
                            idsUserRole:record.get('id')
                        },
                        success:function(response,options){
                            role_effective_store.load();
                        },
                        failure:function(response,options){
                            alert('Error al asociar permiso con usuario')
                        }
                    });
                }
           },
           rowdeselect:function(this_,rowIndex,record){
                if (panel_panel1_panel1_gridpanel_selModel.getCount()!=0){
                    Ext.Ajax.request({
                        url:'user/deattachUserRole.json',
                        params:{
                            id:panel_panel1_panel1_gridpanel_selModel.getSelected().get('id'),
                            idsUserRole:record.get('id')
                        },
                        success:function(response,options){
                            role_effective_store.load();
                        },
                        failure:function(response,options){
                            alert('Error al desasociar permiso del usuario')
                        }
                    });
                }
           }
        }
    });
	
	var group_sm = new Ext.grid.CheckboxSelectionModel({
        singleSelect: false,
        sortable: false,
        checkOnly: false,
        simpleSelect:false,
        listeners:{
           rowselect:function(this_,rowIndex,record){
                if (panel_panel1_panel1_gridpanel_selModel.getCount()!=0){
                    Ext.Ajax.request({
                        url:'user/attachUserGroup.json',
                        params:{
                            id:panel_panel1_panel1_gridpanel_selModel.getSelected().get('id'),
                            idsUserGroup:record.get('id')
                        },
                        success:function(response,options){
                            role_effective_store.load();
                        },
                        failure:function(response,options){
                            alert('Error al asociar usuario con grupo')
                        }
                    });
                }
           },
           rowdeselect:function(this_,rowIndex,record){
                if (panel_panel1_panel1_gridpanel_selModel.getCount()!=0){
                    Ext.Ajax.request({
                        url:'user/deattachUserGroup.json',
                        params:{
                            id:panel_panel1_panel1_gridpanel_selModel.getSelected().get('id'),
                            idsUserGroup:record.get('id')
                        },
                        success:function(response,options){
                            role_effective_store.load();
                        },
                        failure:function(response,options){
                            alert('Error al desasociar permiso del usuario')
                        }
                    });
                }
           }
        }
    });
	 
	function setPanelVisible(panelId,state){
    	var buttonId = panelId.replace('panel','button');
    	var button = Ext.getCmp(buttonId);
    	button.toggle(state,true);
        var panel = Ext.getCmp(panelId);
        if (state)
            panel.show();
        else
            panel.hide();
        panel.ownerCt.doLayout(true,true);
    };
    
 	var user_proxy = new Ext.data.HttpProxy({
        api: {
            read : 'user/get.json',
            create : 'user/post.json',
            update: 'user/put.json',
            destroy: 'user/delete.json'
        }
    });

	var user_store = new Ext.data.Store({
		autoLoad:{params:{start:0,limit:Ext.PagingToolbar.prototype.pageSize}},
        sortInfo:{field:'name',direction:'ASC'},
        remoteSort:true,
        
        reader: new Ext.data.JsonReader(jsonReader_config,User),
        proxy: user_proxy,
        writer: new Ext.data.JsonWriter(jsonWriter_config),
        autoSave: true,
        batch: false
        
	});
	
	var role_store = new Ext.data.Store({
		url:'userrole/get.json',
        reader:new Ext.data.JsonReader(jsonReader_config,UserRole),
        autoLoad:true,
        sortInfo:{field:'message',direction:'ASC'},
        remoteSort:false
	});
	
	var role_sel_store = new Ext.data.Store({
        url:'userrole/get.json',
        baseParams:{idsUser:null},
        reader:new Ext.data.JsonReader(jsonReader_config,UserRole),
        listeners:{
            beforeload: function(){
                panel_panel2_gridpanel.loadMask.show();
            },
            load : function(this_,records,options){
            	var records = [];
                role_store.each(function(record){
                    if(this_.findExact('id',record.get("id"))!=-1){
                        records.push(record);
                    }
                })
                role_sm.suspendEvents(false);
                role_sm.selectRecords(records);
                role_sm.resumeEvents();
                
                panel_panel2_gridpanel.loadMask.hide();
            } 
        }
    });
    
    var group_sel_store = new Ext.data.Store({
        url:'usergroup/get.json',
        reader:new Ext.data.JsonReader(jsonReader_config,UserGroup),
        listeners:{
            beforeload: function(){
                panel_panel1_panel2_gridpanel.loadMask.show();
            },
            load : function(this_,records,options){
                var records = [];
                group_store.each(function(record){
                    if(this_.findExact('id',record.get("id"))!=-1){
                        records.push(record);
                    }
                })
                group_sm.suspendEvents(false);
                group_sm.selectRecords(records);
                group_sm.resumeEvents();
                
                panel_panel1_panel2_gridpanel.loadMask.hide();
            } 
        }
    });
    
	var group_store = new Ext.data.Store({
		url:'usergroup/get.json',
        reader:new Ext.data.JsonReader(jsonReader_config,UserGroup),
        autoLoad:{params:{start:0,limit:Ext.PagingToolbar.prototype.pageSize}},
        sortInfo:{field:'name',direction:'ASC'},
        remoteSort:false
	});
	
	var panel_panel2_gridpanel_colModel = new Ext.grid.ColumnModel({
		columns:[
		    role_sm,
            {id:'message',header:'Permiso',dataIndex:'message',sortable:false}
		]
	});
	
	var panel_panel2_gridpanel = new Ext.grid.GridPanel({
        flex:1,
        border:true,bodyBorder:true,hideBorders:false,
        autoExpandColumn:'message',
    	colModel:panel_panel2_gridpanel_colModel,
    	loadMask:true,
    	store:role_store,
    	stripeRows:false,
    	selModel: role_sm
    });
	
	var panel_panel1_panel2_gridpanel_colModel = new Ext.grid.ColumnModel({
		defaults:{
		  sortable:true
		},
		columns:[
		    group_sm,
            {id:'message',header:'Nombre',dataIndex:'name',sortable:true}
		]
	});
	
	var textField =  new Ext.form.TextField({
        allowBlank: false
    });
    var emailField =  new Ext.form.TextField({
        allowBlank: false,
        vtype: 'email'
    });
    
    function userDelete(grid,rowIndex){
        grid.getStore().removeAt(rowIndex);
    }
    
	var panel_panel1_panel1_gridpanel_colModel = new Ext.grid.ColumnModel({
		defaults:{
		  sortable:true
		},
		columns:[
            {header:'Usuario',dataIndex:'name',sortable:true,editor:textField},
            {header:'Nombre',dataIndex:'firstName',sortable:true,editor:textField},
            {header:'Apellido',dataIndex:'lastName',sortable:true,editor:textField},
            {id:'email',header:'Email',dataIndex:'email',sortable:true,editor:emailField},
            {xtype:'actioncolumn',width:30,items:[
                {tooltip:'Eliminar',icon:iconPath('delete'),handler:userDelete}
            ]}
		]
	});
	
	var panel_panel1_panel1_gridpanel_selModel = new Ext.grid.RowSelectionModel({
       singleSelect:true,
       listeners:{
           rowselect:function(this_,rowIndex,record){
                panel_panel1_panel2.enable();
                panel_panel2.enable();
                panel_panel3.enable();

                role_effective_store.setBaseParam('idsUser',record.id);
                role_effective_store.load();
                role_sel_store.setBaseParam('idsUser',record.id);
                role_sel_store.load();
                group_sel_store.setBaseParam('idsUser',record.id);
                group_sel_store.load();
           },
           rowdeselect:function(this_,rowIndex,record){
                role_effective_store.removeAll();
           	
                role_sm.suspendEvents(false);
                role_sm.clearSelections();
                role_sm.resumeEvents();
                
                group_sm.suspendEvents(false);
                group_sm.clearSelections();
                group_sm.resumeEvents();
                
                panel_panel1_panel2.disable();
                panel_panel2.disable();
                panel_panel3.disable();
           }
       }
    });
    
	var panel_panel1_panel1_gridpanel = new Ext.grid.EditorGridPanel({
        flex:1,
        border:true,bodyBorder:true,hideBorders:false,
        autoExpandColumn:'email',
    	colModel:panel_panel1_panel1_gridpanel_colModel,
    	loadMask:true,
    	bbar:new Ext.PagingToolbar({
            store:user_store,
            items:['->']
        }),
    	selModel:panel_panel1_panel1_gridpanel_selModel,
    	store: user_store
    });
	
	var panel_panel1_panel2_gridpanel = new Ext.grid.GridPanel({
        flex:1,
        border:true,bodyBorder:true,hideBorders:false,
        autoExpandColumn:'message',
    	colModel:panel_panel1_panel2_gridpanel_colModel,
    	loadMask:true,
    	store:group_store,
    	stripeRows:false,
    	sm:group_sm
    });
	
	var panel_panel1_panel1_panel = new Ext.Panel({
        height:100,
        hidden:true,
        buttonAlign:'center'
	});
	
	function onAddUserClick(btn, ev) {
        var u = new User({
            //id: 0,
            name : '',
            firstName: '',
            lastName: '',
            email: ''
        });
        panel_panel1_panel1_gridpanel.stopEditing();
        panel_panel1_panel1_gridpanel.store.insert(0, u);
        panel_panel1_panel1_gridpanel.startEditing(0, 0);
    };
    
	var panel_panel1_panel1 = new Ext.Panel({
    	iconCls:'silk_user',
        layout:'vbox',
        title:'Usuarios',
        frame:true,
        border:true,
        flex:1,
        style:{padding:'5px'},
        layoutConfig:{align:'stretch',pack:'start'},
        tbar:[{
            tooltip:'Nuevo usuario',
            id:'button_new_user',
            text:'Nuevo',
            iconCls:'silk_user_add',
            handler: onAddUserClick
        },'->',{
            tooltip:'Grupos',
            id:'button_group',
            iconCls:'silk_group',
            enableToggle:true,
            pressed:true,
            toggleHandler:function(button,state){
                setPanelVisible('panel_group',state);
            }
        },' ',{
            tooltip:'Permisos',
            id:'button_role',
            iconCls:'silk_page_key',
            enableToggle:true,
            pressed:true,
            toggleHandler:function(button,state){
                setPanelVisible('panel_role',state);
            }
        },' ',{
            tooltip:'Permisos efectivos',
            id:'button_effective_role',
            iconCls:'silk_page_key',
            enableToggle:true,
            pressed:false,
            toggleHandler:function(button,state){
                setPanelVisible('panel_effective_role',state);
            }
        }],
        items:[
           panel_panel1_panel1_panel,
           panel_panel1_panel1_gridpanel
        ]
	});
	 
	 var panel_panel1_panel2 = new Ext.Panel({
    	id:'panel_group',
		iconCls:'silk_group',
        height:216,
        title:'Grupos',disabled:true,
        layout:'fit',
        frame:true,
        style:{padding:'5px'},
        items:[panel_panel1_panel2_gridpanel],
        tools:[
            {id:'close',qtip:'Ocultar',handler:function(event,toolEl,panel,tc){setPanelVisible(panel.getId(),false);}}
        ]
    });
	 
	var panel_panel1 = new Ext.Panel({
        flex:1,
        layout:'vbox',
        layoutConfig:{align:'stretch',pack:'start'},
        items:[
            panel_panel1_panel1,
            panel_panel1_panel2
        ],
        border:false,
        bodyStyle:{backgroundColor:'transparent'},
        style:{backgroundColor:'transparent'}
    });

	var panel_panel2 = new Ext.Panel({
		id:'panel_role',
		iconCls:'silk_page_key',
		frame:true,
        title:'Permisos',
        disabled:true,
        width:200,
        layout:'fit',
        layoutConfig:{align:'stretch',pack:'start'},
        items:panel_panel2_gridpanel,
        tools:[
            {id:'close',qtip:'Ocultar',handler:function(event,toolEl,panel,tc){setPanelVisible(panel.getId(),false);}}
        ],
        style:{padding:'5px'}
    });
    
    var role_effective_store = new Ext.data.Store({
        url:'userrole/get.json',
        reader:new Ext.data.JsonReader(jsonReader_config,UserRole),
        autoLoad:false,
        baseParams:{effective:true},
        sortInfo:{field:'message',direction:'ASC'},
        remoteSort:false
    });
    
    var panel_panel3_gridpanel = new Ext.grid.GridPanel({
        flex:1,
        border:true,
        bodyBorder:true,
        hideBorders:false,
        autoExpandColumn:'message',
        columns:[{id:'message',header:'Permiso',dataIndex:'message',sortable:false}],
        loadMask:true,
        store:role_effective_store,
        stripeRows:false,
        disableSelection:true
    });
    
    var panel_panel3 = new Ext.Panel({
        id:'panel_effective_role',
        iconCls:'silk_page_key',
        frame:true,
        hidden:true,
        title:'Permisos efectivos',
        disabled:true,
        width:200,
        layout:'fit',
        layoutConfig:{align:'stretch',pack:'start'},
        items:panel_panel3_gridpanel,
        tools:[
            {id:'close',qtip:'Ocultar',handler:function(event,toolEl,panel,tc){setPanelVisible(panel.getId(),false);}}
        ],
        style:{padding:'5px'}
    });
	
    var container = new Ext.Panel({
        renderTo:'container',
        layout:'hbox',
        layoutConfig:{align:'stretch',pack:'start'},
        items:[
            panel_panel1,
            panel_panel2,
            panel_panel3
        ],
        border:false,
        bodyStyle:{backgroundColor:'transparent'},
        style:{backgroundColor:'transparent',padding:'0 5px 5px 5px'}
	});
    
    function resize(){
        if (!Ext.isEmpty(container)){
            container.setHeight(Ext.get('container').getHeight());
            container.doLayout();
        }
    }
    Ext.EventManager.onDocumentReady(resize);
    Ext.EventManager.onWindowResize(resize);
    
},window,{single: true});
